<template>
	<div class="main" ref="mainRef">
		<el-container>
			<!-- 搜索框区域  -->
			<el-header>
				<AnimeMiddle ref="SearchRef" @search="search"> </AnimeMiddle>
			</el-header>
			<el-container>
				<el-aside width="200px" style="background-color: rgb(238, 241, 246)">
					<el-menu>
						<el-menu-item-group
							v-for="(sort, index) in showsortList"
							:key="sort.catId"
						>
							<template slot="title"
								><span class="type">{{ sort.catName }}</span></template
							>
							<el-menu-item
								v-for="(name, index) in sort.children"
								:key="index"
								@click="handleSelect(name.catId)"
								>{{ name.catName }}</el-menu-item
							>
							<div
								v-if="sortList[index].children.length > 3"
								@click="changeFoldState(index)"
								class="ab"
							>
								<span style="color: deepskyblue; margin-left: 10px">{{
									brandFold[index] ? '更多' : '收起'
								}}</span>
							</div>
						</el-menu-item-group>
					</el-menu>
				</el-aside>
				<el-container>
					<el-main>
						<div class="main-top">
							<div
								style="
									position: relative;
									width: 940px;
									height: 50px;
									margin: auto;
								"
							>
								<el-row>
									<el-button
										size="medium"
										:class="{
											one: oneIndex === index,
											a: oneIndex === index,
											b: oneIndex != index,
										}"
										v-for="(item, index) in list"
										:key="item.id"
										@click="sift(index)"
									>
										{{ item.name }}
										<i v-show="item.id === 4" class="el-icon-d-caret"></i>
									</el-button>
								</el-row>
								<label for="dd" class="add">
									<div class="price" id="price">
										<el-input
											v-model="minPrice"
											placeholder="最低价（￥）"
											size="medium"
											type="number"
											@focus="confirm()"
											@blur="confirm()"
										></el-input>
										<el-input
											v-model="maxPrice"
											placeholder="最高价（￥）"
											type="number"
											size="medium"
											@focus="confirm()"
											@blur="confirm()"
										></el-input>
										<el-button
											:class="{ a: true, confirm_btn: confirm1 }"
											size="mini"
											id="dd"
											@click="priceInquiry"
											>确认</el-button
										>
									</div>
								</label>
								<div class="all">
									<i
										class="fa fa-th-large fa-lg"
										:class="[{ a: fa }]"
										@click="fa1"
									></i>
									<i
										class="fa fa-th-list fa-lg"
										:class="[{ a: !fa }]"
										@click="fa1"
									></i>
								</div>
							</div>

							<!-- 商品展示区域 -->
							<div class="figures" v-if="longitudinal">
								<FigureLongitudinalVue
									v-for="item in figuresArray"
									v-if="item.goodsState == 1 && item.goodsNumber > 0"
									:key="item.id"
									:figures="item"
								></FigureLongitudinalVue>
							</div>
							<div class="figures" v-else>
								<FigureCrossVue
									v-for="item in figuresArray"
									v-if="item.goodsState == 1 && item.goodsNumber > 0"
									:key="item.id"
									:figures="item"
								></FigureCrossVue>
							</div>
						</div>
					</el-main>
					<el-footer>
						<div class="load">
							<van-loading v-if="loading" color="#1989fa" size="60" />
							<p v-if="noMore">没有更多了</p>
						</div>
					</el-footer>
				</el-container>
			</el-container>
		</el-container>
	</div>
</template>

<script>
	import FigureCrossVue from '@/components/front/FigureCross.vue'
	import FigureLongitudinalVue from '@/components/front/FigureLongitudinal.vue'
	import AnimeMiddle from '@/components/front/AnimeMiddle.vue'
	export default {
		data() {
			return {
				sortList: [],
				oneIndex: 0,
				fa: true,
				longitudinal: true,
				minPrice: '',
				maxPrice: '',
				list: [
					{ id: 1, name: '销量排序', sort: 'asc', sortName: 'quantitySold' },
					{ id: 2, name: '综合排序', sort: 'asc', sortName: 'all' },
					{ id: 3, name: '评价排序', sort: 'asc', sortName: 'star' },
					{ id: 4, name: '价格排序', sort: 'asc', sortName: 'goodsPrice' },
				],
				figuresList: [],
				showsortList: '',
				brandFold: [],
				loading: false,
				queryInfo: {
					query: '',
					pagenum: 1,
					pagesize: 10,
					sort: 'asc',
					sortName: 'quantitySold',
					minPrice: 0,
					maxPrice: 0,
					goodsCat: '',
				},
				total: 0,
				confirm1: false,
			}
		},
		created() {
			this.do()
		},
		mounted() {
			// 监听滚动事件
			window.addEventListener('scroll', this.handleScroll)
		},

		methods: {
			//刷新商品函数
			async handleScroll() {
				// 获取滚动条距离底部的距离
				const scrollHeight =
					document.documentElement.scrollHeight || document.body.scrollHeight
				const scrollTop =
					window.pageYOffset ||
					document.documentElement.scrollTop ||
					document.body.scrollTop
				const clientHeight =
					document.documentElement.clientHeight || document.body.clientHeight
				const scrollBarHeight = scrollHeight - scrollTop - clientHeight
				// 计算滚动条距离底部的距离
				const distanceToBottom = scrollBarHeight

				if (distanceToBottom <= 1) {
					if (!this.noMore) {
						this.loading = true
						this.queryInfo.pagenum += 1
						let figures = await this.$api.sort.getfigures(this.queryInfo)
						figures.data.data.forEach((item) => {
							item.pics = item.pics ? item.pics.split(',') : []
							item.detailPics = item.detailPics ? item.detailPics.split(',') : []
							item.manyAttrs.forEach((item) => {
								item.attrVals = item.attrVals ? item.attrVals.split(' ') : []
								item.addPrice = item.addPrice ? item.addPrice.split(' ') : []
								item.urls = item.urls ? item.urls.split(' ') : []
								item.checkeds = item.checkeds
									? item.checkeds.split(' ').map((val) => val === 'true')
									: []
							})
							if (item.pics.length > 0) {
								this.$api.rear_end.download(item.pics[0]).then((res) => {
									let url = window.URL.createObjectURL(
										new Blob([res.data], { type: 'image/jpeg' })
									)
									item.pics = url
								})
							}
						})
						const a = figures.data.data
						a.forEach((item) => {
							this.figuresList.push(item)
						})
						this.loading = false
					}
				}
			},
			fa1() {
				this.fa = !this.fa
				this.longitudinal = !this.longitudinal
			},
			changeFoldState(index) {
				this.brandFold[index] = !this.brandFold[index]
				var obj = {}
				obj = JSON.parse(JSON.stringify(this.sortList))
				let newArr = []
				for (var i = 0; i < this.brandFold.length; i++) {
					if (this.brandFold[i]) {
						if (obj.length < 3) {
							newArr.push(obj[i])
							continue
						}
						let s = []
						for (var j = 0; j < 3; j++) {
							let item = obj[i].children[j]
							s.push(item)
						}
						newArr.push(obj[i])
						newArr[i].children = s
					} else {
						newArr[i] = obj[i]
					}
				}
				this.showsortList = newArr
			},
			//获取商品数据
			async getGoods() {
				//商品信息
				let figures = await this.$api.sort.getfigures(this.queryInfo)
				let data = figures.data
				data.data.forEach((item) => {
					item.pics = item.pics ? item.pics.split(',') : []
					item.detailPics = item.detailPics ? item.detailPics.split(',') : []
					item.manyAttrs.forEach((item) => {
						item.attrVals = item.attrVals ? item.attrVals.split(' ') : []
						item.addPrice = item.addPrice ? item.addPrice.split(' ') : []
						item.urls = item.urls ? item.urls.split(' ') : []
						item.checkeds = item.checkeds
							? item.checkeds.split(' ').map((val) => val === 'true')
							: []
					})
					if (item.pics.length > 0) {
						this.$api.rear_end.download(item.pics[0]).then((res) => {
							let url = window.URL.createObjectURL(
								new Blob([res.data], { type: 'image/jpeg' })
							)
							item.pics = url
						})
					}
				})
				this.figuresList = data.data
				this.total = figures.data.map.total
				this.$forceUpdate()
			},
			async do() {
				//商品分类
				let res = await this.$api.sort.classified()
				this.sortList = res.data.data
				this.showsortList = JSON.parse(JSON.stringify(this.sortList))
				this.showsortList.forEach(() => {
					this.brandFold.push(false)
				})
				//获取商品数据
				this.getGoods()
			},
			//点击排序
			sift(index) {
				if (index === this.oneIndex) {
					if (this.list[index].sort === 'asc') this.list[index].sort = 'desc'
					else this.list[index].sort = 'asc'
				}
				this.queryInfo.sort = this.list[index].sort
				this.queryInfo.sortName = this.list[index].sortName
				this.getGoods()
				this.oneIndex = index
			},
			//左侧选择
			handleSelect(catId) {
				this.queryInfo.goodsCat = catId
				this.queryInfo.pagenum = 1
				this.queryInfo.pagesize = 10
				this.getGoods()
			},
			//价格查询
			priceInquiry() {
				if (
					(this.maxPrice.trim() !== '' && this.maxPrice - 0 >= 0) ||
					(this.minPrice.trim() !== '' && this.minPrice - 0 >= 0)
				) {
					if (this.maxPrice.trim() !== '' && this.minPrice.trim() !== '') {
						if (this.maxPrice - 0 < this.minPrice - 0) {
							this.$message.error('最大值要大于或者等于最小值！')
							return
						}
					}
					this.queryInfo.maxPrice = this.maxPrice.trim()
					this.queryInfo.minPrice = this.minPrice.trim()
					this.getGoods()
				} else {
					this.$message.error('价格不能是负数！')
				}
			},
			//确认框的显隐
			confirm() {
				this.confirm1 = !this.confirm1
			},
			//搜索查询
			search(val) {
				this.queryInfo.query = val
				this.queryInfo.pagenum = 1
				this.queryInfo.pagesize = 10
				this.queryInfo.goodsCat = ''
				this.queryInfo.sort = 'asc'
				this.queryInfo.sortName = ' '
				this.figuresList = []
				this.getGoods()
			},
		},
		components: {
			FigureLongitudinalVue,
			FigureCrossVue,
			AnimeMiddle,
		},
		computed: {
			noMore() {
				return this.figuresList.length >= this.total
			},
			disabled() {
				return this.loading || this.noMore
			},
			figuresArray() {
				return this.figuresList
			},
		},
	}
</script>

<style scoped lang="less">
	.el-aside {
		background-color: transparent;
		background-color: #d3dce6;
		color: #333;
		text-align: center;
		line-height: 200px;
		height: auto;
	}
	.el-main {
		background-color: #f9faf9;
		color: #333;
		text-align: center;
		line-height: 160px;
		min-height: 753px;
	}
	.el-row {
		position: absolute;
		top: -62px;
		width: 420px;
		height: 50px;
	}
	.row {
		float: left;
	}
	.main-top {
		overflow: hidden;
	}
	.main-top .el-button {
		color: #000;
		border: 1px solid #cccccc;
		margin-left: -3px;
	}
	.main-top .el-button:hover {
		color: #000;
		background-color: #ff5000;
	}
	.type {
		font-size: 20px;
	}
	.a {
		background-color: #ff5000;
	}
	.b {
		background-color: #f5f5f5;
	}
	.c {
		width: 150px;
	}
	.ab {
		width: 200px;
		height: 40px;
		margin-top: -90px;
		margin-bottom: 100px;
	}
	.one:hover {
		background-color: #ff5000;
	}
	.el-icon-caret-bottom {
		position: relative;
		top: 12px;
		left: -14px;
	}
	.add {
		width: 200px;
		height: 50px;
		position: relative;
		top: -62px;
		left: 0px;
	}
	.add .el-input {
		width: 120px;
		height: 40px;
	}

	.price {
		position: absolute;
		left: 0px;
		top: 0px;
		width: 260px;
		height: 100px;
	}
	.price .el-button {
		display: none;
	}
	.price .el-button:hover {
		display: inherit;
	}
	.confirm_btn {
		display: inherit !important;
	}
	.all {
		position: absolute;
		top: -62px;
		width: 100px;
		height: 50px;
		margin-left: 780px;
	}
	#dd {
		position: relative;
		top: -92px;
		left: 260px;
	}

	.fa {
		width: 35px;
		height: 35px;
		border-radius: 10px;
		line-height: 35px;
		border: 1px solid #cccccc;
	}
	.figures {
		margin-left: 10%;
	}
	.el-footer {
		text-align: center;
		line-height: 60px;
	}
	.el-header {
		height: 0px !important;
	}
</style>
